﻿using Core;
using UnityEngine;

namespace Core
{
    /// <summary>
    /// 序列帧动画组件
    /// </summary>
    public class Sprite1DirAnimationComponent : Core.Component, IAwake, IFrameUpdate
    {
        protected SpriteRenderer renderer;
        protected Anim1DirData animConf;

        protected int currFrame;
        protected int startFrame;

        public virtual void Awake() { }

        public void Tick()
        {
            var index = SysTime.FrameCount - startFrame;
            if (currFrame == index)
            {
                return;
            }

            SetFrame(index);
        }

        public virtual void Play(string res_path)
        {
            animConf = null;
            startFrame = SysTime.FrameCount;

            Load(res_path).Coroutine();

            SetFrame(0);
        }

        protected virtual void SetFrame(int frame)
        {
            currFrame = frame;

            if (renderer == null || animConf == null)
            {
                return;
            }

            var len = animConf.Sprites.Length;
            if (len == 0)
            {
                return;
            }

            frame = Mathf.Min(currFrame, len - 1);

            renderer.sprite = animConf.Sprites[frame];
        }

        private async ETVoid Load(string res_path)
        {
            var asset = await G.Res.LoadAsync(res_path);
            animConf = asset?.Obj as Anim1DirData;
            if (animConf == null)
            {
                log.err($"Player动画资源不存在 anim_res={res_path}");
                return;
            }
        }
    }
}